package org.linlinjava.litemall.admin.service;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.linlinjava.litemall.admin.dto.FormulaDTO;
import org.linlinjava.litemall.admin.dto.MaterialAttribute;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.Formula;
import org.linlinjava.litemall.db.domain.FormulaMaterial;
import org.linlinjava.litemall.db.domain.Material;
import org.linlinjava.litemall.db.service.FormulaMaterialService;
import org.linlinjava.litemall.db.service.FormulaService;
import org.linlinjava.litemall.db.service.MaterialService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.GOODS_NAME_EXIST;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.MATERIAL_NOT_EXIST;

/**
 * Author tony
 * Description
 * Date 2020/10/23 0:21
 */
@Service
public class AdminFormulaService {

    private static Logger logger = LoggerFactory.getLogger(AdminFormulaService.class);


    @Resource
    private FormulaService formulaService;

    @Resource
    private FormulaMaterialService formulaMaterialService;

    @Resource
    private MaterialService materialService;

    @Transactional
    public Object addOne(FormulaDTO brand) {
        if(CollectionUtils.isEmpty(brand.getAttributes())){
            return ResponseUtil.fail(MATERIAL_NOT_EXIST,"原料不能为空");
        }

        Formula formula = brand.getFormula();
        List<MaterialAttribute> attributes = brand.getAttributes();

        String name = formula.getName();
        if (formulaService.checkExistByName(name)) {
            return ResponseUtil.fail(GOODS_NAME_EXIST, "配方名已经存在");
        }
        if (formulaService.checkExistByCode(formula.getCode())) {
            return ResponseUtil.fail(GOODS_NAME_EXIST, "配方编码已经存在");
        }
        formulaService.add(formula);
        Integer formulaId = formula.getId();
        BigDecimal totalPrice=BigDecimal.ZERO;
        List<Integer> materialIds = Lists.newArrayList();
        Map<Integer,BigDecimal> maps = Maps.newHashMap();
        for(MaterialAttribute material:attributes){
            materialIds.add(material.getMaterialId());
            maps.put(material.getMaterialId(),material.getAmount());
            FormulaMaterial formulaMaterial = new FormulaMaterial();
            formulaMaterial.setfId(formulaId);
            formulaMaterial.setmId(material.getMaterialId());
            formulaMaterial.setAmount(material.getAmount());
            formulaMaterialService.add(formulaMaterial);
        }
        List<Material> materials = materialService.queryByIds(materialIds);
        for(Material m :materials){
            BigDecimal price = m.getPrice();
            BigDecimal amount = maps.get(m.getId());
            totalPrice=totalPrice.add(price.multiply(amount));
        }
        Formula f = new Formula();
        f.setPrice(totalPrice);
        f.setId(formulaId);
        formulaService.updateById(f);
        return ResponseUtil.ok();
    }

    @Transactional
    public Object updateOne(FormulaDTO brand) {
        if(CollectionUtils.isEmpty(brand.getAttributes())){
            return ResponseUtil.fail(MATERIAL_NOT_EXIST,"原料不能为空");
        }

        Formula formula = brand.getFormula();
        Formula formulaentity = new Formula();
        formulaentity.setId(formula.getId());
        formulaentity.setName(formula.getName());
        formulaentity.setBrief(formula.getBrief());
        formulaentity.setNumber(formula.getNumber());
        formulaentity.setCode(formula.getCode());

        formulaService.updateById(formulaentity);

        Integer formulaId = formula.getId();
        BigDecimal totalPrice=BigDecimal.ZERO;

        List<MaterialAttribute> attributes = brand.getAttributes();

        formulaMaterialService.deleteByFid(formulaId);

        List<Integer> materialIds = Lists.newArrayList();
        Map<Integer,BigDecimal> maps = Maps.newHashMap();
        for(MaterialAttribute material:attributes){
            materialIds.add(material.getMaterialId());
            maps.put(material.getMaterialId(),material.getAmount());
            FormulaMaterial formulaMaterial = new FormulaMaterial();
            formulaMaterial.setfId(formulaId);
            formulaMaterial.setmId(material.getMaterialId());
            formulaMaterial.setAmount(material.getAmount());
            formulaMaterialService.add(formulaMaterial);
        }
        List<Material> materials = materialService.queryByIds(materialIds);
        for(Material m :materials){
            BigDecimal price = m.getPrice();
            BigDecimal amount = maps.get(m.getId());
            totalPrice=totalPrice.add(price.multiply(amount));
        }
        Formula f = new Formula();
        f.setPrice(totalPrice);
        f.setId(formulaId);
        formulaService.updateById(f);
        return ResponseUtil.ok();
    }


    /**
     * Excel 解析成 员工数据集合
     *
     * @param file
     * @return
     */
    public synchronized Boolean excel2Employee(MultipartFile file) {
        List<Material> list = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            ExcelReader excelReader = ExcelUtil.getReader(inputStream);
            List<Map<String,Object>> readAll = excelReader.readAll();
            for (Map<String,Object> objects : readAll) {
                String code = String.valueOf(objects.get("原料编码"));
                String name = String.valueOf(objects.get("原料名称"));
                String unit = String.valueOf(objects.get("原料单位"));
                String price = String.valueOf(objects.get("原料单价"));
                BigDecimal bPrice;
                try {
                    bPrice = new BigDecimal(price);
                }catch (Exception e){
                    continue;
                }
                Material material = new Material();
                LocalDateTime now = LocalDateTime.now();
                material.setName(name);
                material.setUnit(unit);
                material.setPrice(bPrice);
                material.setCode(code);
                material.setAddTime(now);
                material.setUpdateTime(now);
                list.add(material);
            }
            materialService.addAll(list);
            return true;
        } catch (IOException e) {
            logger.error("导入excel  material失败");
        }
        return false;
    }
}
